package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.ArticleApi;
import com.jmp.base.DynamicApi;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.DynamicFeign;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import com.jmp.api.dto.*;
import one.stand.dto.*;
import one.stand.enums.LoginEnum;
import one.stand.mapper.ArticleApiCrmMapper;
import one.stand.mapper.ArticleMapperExt;
import one.stand.mapper.TemplateApiMapper;
import one.stand.model.*;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.sys.ArticleTypeService;
import one.stand.service.sys.SysDictValueService;
import one.stand.service.sys.UserContentService;
import one.stand.service.user.UserAdminService;
import one.stand.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "红木头条")
@RestController
@RequestMapping("crmApi/lead")
public class LeadController {
    @Autowired
    private DynamicFeign dynamicFeign;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private TemplateApiMapper templateApiMapper;
    @Autowired
    private ArticleApiCrmMapper articleApiCrmMapper;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private ArticleMapperExt articleMapperExt;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private SysDictValueService sysDictValueService;

    @ApiOperation(value = "置顶、轮播、海报")
    @PostMapping("")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LeadResponse> top() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        final Integer companyId = optUser.getCompanyId();
        PageHelper.startPage(1, 3);
        List<Article> articleList = articleApiCrmMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_TOP, null);
        List<LeadResponse.Top> articles = ConvertUtils.list(articleList, article -> {
            ArticleType type = articleTypeService.get(article.getTypeId());
            return LeadResponse.Top.builder()
                    .id(article.getId())
                    .title(article.getTitle())
                    .top("置顶")
                    .type(type.getName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .build();
        });

        PageHelper.startPage(1, 5);
        List<Article> bannerList = articleApiCrmMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_BANNER, null);
        List<LeadResponse.Banner> banners = ConvertUtils.list(bannerList, article -> {
            ArticleType type = articleTypeService.get(article.getTypeId());
            return LeadResponse.Banner.builder()
                    .id(article.getId())
                    .title(article.getTitle())
                    .pic(article.getShareCard())
                    .type(type.getName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .build();
        });

        PageHelper.startPage(1, 3);
        List<Template> templates = templateApiMapper.selectList(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_CARD);
        List<LeadResponse.Card> cards = ConvertUtils.list(templates, template -> {
            TemplateGetRequest getRequest = TemplateGetRequest.builder()
                    .templateId(template.getId())
                    .cardId(optUser.getCardId())
                    .build();
            ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get(getRequest);
            String imgUrl = getResponseResultModel.isSuccess() ? getResponseResultModel.getData().getImageUrl() : null;
            return LeadResponse.Card.builder()
                    .pic(imgUrl)
                    .build();
        });

        LeadResponse response = LeadResponse.builder()
                .tops(articles)
                .banners(banners)
                .cards(cards)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "首页")
    @PostMapping("index")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LeadIndexResponse> index(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        final Integer companyId = optUser.getCompanyId();

        PageHelper.startPage(1, 3);
        List<Article> tops = articleApiCrmMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_TOP, null);
        PageHelper.startPage(1, 5);
        tops.addAll(articleApiCrmMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_BANNER, null));
        List<Integer> idsExclude = ConvertUtils.list(tops, Article::getId);
        String excludeIds = SqlUtil.in(idsExclude);

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Article> articleList = articleApiCrmMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, null, excludeIds);
        PageResponse2<LeadIndexResponse.Index> articles = ConvertUtils.page2(articleList, article -> {
            ArticleType type = articleTypeService.get(article.getTypeId());
            return LeadIndexResponse.Index.builder()
                    .id(article.getId())
                    .title(article.getTitle())
                    .type(type.getName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .build();
        });

        LeadIndexResponse response = LeadIndexResponse.builder()
                .indexs(articles)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "详情")
    @PostMapping("detail")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LeadDetailResponse> detail(@RequestAttribute LeadDetailRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        AssertUtil.nonNull(article, ResultEnum.PARAM_CHECK, "文章不存在");
        AssertUtil.isTrue(ArticleApi.STATUS_UP == article.getStatus(), ResultEnum.PARAM_CHECK, "文章已下架");

        UserDto user = userAdminService.get(optUser.getUserId());
        BusinessCard cardModel = businessCardBaseService.getCustomer(optUser.getCardId());
        Company company = companyBaseService.getById(optUser.getCompanyId());
        AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                .companyId(optUser.getCompanyId())
                .loginEnum(LoginEnum.USER)
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
        String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;

        LeadDetailResponse response = LeadDetailResponse.builder()
                .img(user.getUserImg())
                .name(user.getName())
                .position(cardModel.getPosition())
                .companyName(company.getCompanyName())
                .title(article.getTitle())
                .origin(article.getOriginName())
                .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                .content(article.getContent())
                .adContent(article.getAdContent())
                .originUrl(article.getOriginUrl())
                .shareUrl(getH5Url(article.getId(), cardModel.getCardId(), null, null, null))
                .shareImg(article.getShareCard())
                .subTitle(article.getSubtitle())
                .wechatId(wechatId)
                .oneWechat(companyBaseService.isOneWechat(optUser.getCompanyId()))
                .hasWxcode(StringUtils.isNoneBlank(cardModel.getWxCode()))
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "分享海报")
    @PostMapping("bill")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<LeadBillResponse> bill(@RequestAttribute LeadBillRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        String h5Url = getH5Url(request.getArticleId(), optUser.getCardId(), request.isHasName(), request.isHasTel(), request.isHasWxcode());

        Article article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        TemplateApi.Type type = TemplateApi.Type.valueOf("ID_CRM_APP_ARTICLE_" + article.getTemplateType());//根据选择

        TemplateGet2Request getRequest = TemplateGet2Request.builder()
                .templateType(type)
                .cardId(optUser.getCardId())
                .articleId(request.getArticleId())
                .articleH5Url(h5Url)
//                .configExclude(configExclude)
                .build();
        ResultModel<TemplateGetResponse> templateGetResponseResultModel = templateFeign.get2(getRequest);
        AssertUtil.isTrue(templateGetResponseResultModel);
        LeadBillResponse response = LeadBillResponse.builder()
                .bill(templateGetResponseResultModel.getData().getImageUrl())
                .build();

        return ResultModel.success(response);
    }

    @ApiOperation(value = "分享 动态")
    @PostMapping("dynamic")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel dynamic(@RequestAttribute LeadDynamicRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        DynamicSaveRequest saveRequest = DynamicSaveRequest.builder()
                .companyId(optUser.getCompanyId())
                .createUserId(optUser.getUserId())
                .type(DynamicApi.TYPE_ARTICLE)
                .title(article.getTitle())
                .details(article.getContent())
                .photos(article.getShareCard())
                .relateType(DynamicApi.RELATE_ID_ARTICLE)
                .relateId(request.getArticleId())
                .build();
        dynamicFeign.save(saveRequest);

        return ResultModel.success();
    }

    @ApiOperation(value = "转发统计")
    @PostMapping("forward")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel forward(@RequestAttribute LeadBillRequest request) {

        articleMapperExt.updateForward(request.getArticleId());

        return ResultModel.success();
    }

    private String getH5Url(Integer articleId, Integer cardId, Boolean hasName, Boolean hasTel, Boolean hasWxcode) {
        DictDto articleH5Dict = sysDictValueService.get2(SysDictValueService.Type.CONFIG, SysDictValueService.TypeNameConfig.article_h5.name());
        String h5Url = String.format(articleH5Dict.getValue(), articleId, cardId);
        if (Objects.nonNull(hasName)) {
            h5Url = h5Url + "&name=" + hasName;
        }
        if (Objects.nonNull(hasTel)) {
            h5Url = h5Url + "&mobile=" + hasTel;
        }
        if (Objects.nonNull(hasWxcode)) {
            h5Url = h5Url + "&wxcode=" + hasWxcode;
        }
        return h5Url;
    }
}
